<template>
    <div class="page-wrap">
        <!-- <div style="color: rgb(27, 76, 184);margin-bottom: 15px">
            <div class="addressIcon"></div>
            <span>当前位置：</span>
            <span style="cursor: pointer" @click="returnImage">图标管理</span>
            <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
            <span style="color: #333">{{titleText}}</span>
        </div> -->
        <div class="page-content" :style="{height:contentHei}">
            <div class="img-header">
                <div style="font-weight: 700;font-size: 18px">{{titleText}}</div>
            </div>
            <Divider />
            <div class="content-wrap">
                <Form ref="creatIconFormValidate" :model="creatIconFormValidate" :rules="creatIconRuleValidate"
                      :label-width="100" style="width: 500px">
                    <FormItem label="名称" prop="name">
                        <Input v-model.trim="creatIconFormValidate.name" placeholder="图标名称长度为1—128个字符"></Input>
                    </FormItem>
                    <FormItem label="可见范围" prop="isshare">
                        <RadioGroup v-model="creatIconFormValidate.isshare">
                          <Radio label="range">平台</Radio>
                          <Radio label="system">系统</Radio>
                          <Radio label="company">单位</Radio>
                          <Radio label="person">个人</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="图标类型" prop="type">
                        <Select filterable 
							style="width: 200px;"
								v-model="creatIconFormValidate.type" 
								placeholder="请选择类型"  :disabled="!showUploadFile||showPath!==''"
								@on-change="changeRange"
								:not-found-text="loadingRange ? '加载中...' : '无匹配数据'"
								label-in-value 
								filterable
								class="experimental-group">
								<Option v-for="(type,index) in pictureType" :title="type.dictname" :value="type.dictid" 
									:key="type.dictid" :label="type.dictname">{{type.dictname}}</Option>
							</Select>
                    </FormItem>
                    <FormItem label="描述" prop="desc">
                        <Input v-model.trim="creatIconFormValidate.desc" type="textarea" :maxlength="200" :autosize="{minRows: 2,maxRows: 5}" placeholder="描述"></Input>
                    </FormItem>
                    <FormItem v-show="showUploadFile" label="图标" prop="path" class="ivu-form-item-required">
                        <ItemUpload 
                            :disabled="!creatIconFormValidate.type"
                            type="images" 
                            :format ="format"
                            :filePath.sync="creatIconFormValidate.path"
                            :uploadLoading.sync = "isUploading"
                            >
                            <template slot="tooltip">
                                <p>请先选择图标类型再上传图标</p>
                            </template>
                        </ItemUpload>
                        <!-- <Upload
                            ref="uploadIcon"
                            v-model="creatIconFormValidate.file"
                            :format = "format"
                            :action="upLoadIconUrl"
                            :on-format-error = "handleFormatError"
                            :on-exceeded-size="onExceededSize"
                            :on-remove="removeFile"
                            :on-progress="uploadProgrress"
                            :show-upload-list="false"
                            :before-upload="handleUploadIcon"
                            :on-success = "onUploadSuccess">
                            <Button  icon="ios-cloud-upload-outline" :disabled="setDisabled||creatIconFormValidate.type==''">上传图标</Button>
                             
                            <span v-if="showPath" style="width:auto;height:30px;margin-left: 50px;vertical-align: middle;">{{showPath}}</span>
                        </Upload>
                        <div></div>
                        <Poptip class="too" popper-class="tooltipclass" theme="dark" placement="top" width="400" :transfer='true' trigger="hover">
                            <Icon type="ios-alert" class="ios-alert" />
                                <div class="api" slot="content">
                                    <p style="white-space: normal;">请先选择图标类型再上传图标。3D模型支持'glb'格式， 封面、头像图标、其他支持'jpg','jpeg','png'格式， logo支持'png'格式</p>
                                </div>
                        </Poptip> -->
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="submitBtn('creatIconFormValidate')" :loading="addIconBtnLoading" :disabled="setDisabled || isUploading">确定</Button>
                        <Button @click="creatIconHandleReset('creatIconFormValidate')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Form>
            </div>
        </div>
    </div>
</template>
<script>
    import {experType} from '@/api/dict.js'
    import {getIconData,modifyIcon,createIcon} from '@/api/icon.js'
    import {validateName1,validateNameCustom } from '@/libs/reg.js'
    import ItemUpload from '@/components/item-upload/single';
    export default {
        components:{ItemUpload},
        data () {
            const validateName = (rule, value, callback) => {
                if (value) {
                    validateNameCustom(rule, value, callback, 128)
                } else {
                    callback();
                }
            };
            return {
                uploadSize:10240,
                format:[],
                loadingRange:false,
                pictureType:[],
                fullHeight: document.documentElement.clientHeight,
                fullWidth: document.documentElement.clientWidth,
                contentHei:'auto',
                upLoadIconUrl:`${this.baseURL}/minio/upload`,
                // 先判断状态
                isCreate:true,
                receiveData:{},
                showUploadFile:true,
                iconId:'',
                // 页面标题
                titleText:'',
                // 表单
                creatIconFormValidate:{
                    name:'',
                    isshare:'company',
                    desc:'',
                    path:'',
                    type:''
                },
                creatIconRuleValidate:{
                    name: [
                        { required: true, max: 128, message: '图标名称长度为1—128个字符', trigger: 'change' },
                        { validator: validateName, trigger: 'change' }
                    ],
                    isshare: [
                        { required: true, message: '可见范围不能为空', trigger: 'change' }
                    ],
                    type: [
                        { required: true, message: '图标类型不能为空', trigger: 'change' }
                    ],
                    desc:[
                        { max: 200, message: '描述长度不得超过200个字符', trigger: 'change' },
                    ],
                    path:[
                        {required: true,message: '请上传文件',trigger: 'change'}
                    ]
                },
                addIconBtnLoading:false,
                setDisabled:false,
                imgUrl:'' ,//icon上传成功后的路径
                showPath:'',
                isUploading:false //是否正在上传
            }
        },
        beforeRouteLeave (to, from, next) {
            if(to.path === '/icon'){
                //to.query.page = this.$route.query.page
                next()
            }else {
            	//跳转至非图标页面，清空存储的查询条件
				sessionStorage.removeItem("queryObj");
                next()
            }
        },
        created(){

        },
        mounted(){
            // 是创建还是修改
            if(this.$route.query.action === 'create'){
                this.isCreate = true
                this.titleText = '创建图标'
                this.showUploadFile = true
            }else if(this.$route.query.action === 'modify'){
                this.isCreate = false
                this.showUploadFile = false
                this.titleText = '修改图标'
                this.iconId = this.$route.query.id
                this.getIconInfo()
            }
            this.addBreadItem({ name: this.titleText });
            this.setStyle()
            window.onresize = () => {
                this.setStyle()
            }
            this.experType()
        },
        methods:{
            changeRange(val){
                if(!val) return
                if(val.value=='Covertitle'||val.value=='other'||val.value=='HEAD'){
                    this.uploadSize=10240
                    this.format=['jpg','jpeg','png']
                } else if(val.value=='logo'){
                    this.format=['png']
                    this.uploadSize=10240
                } else if(val.value == '3DModel'){
                    this.format=['glb']
                    this.uploadSize=51200
                }else{
                    this.format=['jpg','jpeg','png']
                }
            },
            experType(){
                this.loadingRange=true
                experType('picture_type').then((data) => {
						if(data.code == 1) {
							let attribute = data.attribute;
							this.pictureType = attribute.attribute[0].dictEntryList;
							this.pictureType.forEach(dict => {
								dict.key = dict.dictid;
								dict.value = dict.dictname;
							})
                            this.loadingRange=false
						}
					})
            },
            // 设置高度
            setStyle(){
                window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
                this.fullHeight = window.fullHeight;
                this.fullWidth = window.fullWidth;
                this.contentHei =   this.fullHeight - 60 - 21 +'px'  // 80是头部高度  60是上下padding
            },
            // 返回icon管理
            returnImage(){
                this.$router.push({
                    name: 'icon',
                    query:{
                        page:this.$route.query.page,
                    }
                })
            },
            // 获取icon数据
            getIconInfo(){
                let params = {
                    id:this.iconId,
                }
                let query = {
                    pageIndex:1,
                    pageSize:10,
                }
                getIconData(params,query)
                    .then(res=>{
                        if(res.data.code === 1){
                            let pageList = res.data.data.items[0];
                            this.creatIconFormValidate.name = pageList.name
                            this.creatIconFormValidate.isshare = pageList.visibility
                            this.creatIconFormValidate.desc = pageList.description?pageList.description:'';
                            this.creatIconFormValidate.type = pageList.type?pageList.type:'';
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            clearFileList(){
                this.fileList = []
            },
            // 提交按钮
            submitBtn(name){
                if(this.isCreate){
                    this.creatIconHandleSubmit(name)
                }else {
                    this.modifyIcon(name)
                }
            },
            // 创建
            creatIconHandleSubmit(name){
                let iconDto = {
                    type:this.creatIconFormValidate.type,
                    name:this.creatIconFormValidate.name,
                    visibility:this.creatIconFormValidate.isshare,
                    description:this.creatIconFormValidate.desc,
                    path:this.creatIconFormValidate.path,
                }
                for (let key in iconDto) {
                    if (!iconDto[key]) {
                        iconDto[key] = null
                    }
                }
                // let params = this.$Qs.stringify(param, { skipNulls: true })
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        // let formData = new window.FormData()
                        // formData.append('file',this.creatIconFormValidate.file);
                        this.addIconBtnLoading = true
                        this.setDisabled = true
                        // this.axios.post(`${this.baseURL}/virtual/icon/fileUpload?${params}`,formData,{headers:{'Content-type': 'multipart/form-data'}})
                        createIcon(iconDto)
                            .then(res=>{
                                if(res.data.code == 1){
                                    this.$Message.success({
                                        content:'上传成功',
                                        duration:3,
                                    })
                                    this.creatIconFormValidate.file = null
                                    setTimeout(()=>{
                                        this.returnImage()
                                    },3000)
                                }else {
                                    this.$Message.error({
                                        content:res.data.message,
                                        duration:3,
                                    })
                                    this.setDisabled = false
                                }
                                this.addIconBtnLoading = false
                            })
                            .catch(err=>{
                                console.log(err)
                                this.addIconBtnLoading = false
                                this.setDisabled = false
                                this.$Message.error('服务器连接失败！')
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            onExceededSize(file){
                this.creatIconFormValidate.file = null
                if(this.creatIconFormValidate.type=='3DModel'){
                    this.$Message.error({
                        content: '请选择小于50MB的glb文件',
                        duration: 3,
                    })
                
                }else{
                     this.$Message.error({
                        content: '请选择小于10MB的图片',
                        duration: 3,
                    })
                }

            },
            handleFormatError (file) {
                this.creatIconFormValidate.file = null
                this.$Message.error({
                    content: '请选择对应类型格式的文件',
                    duration: 3,
                })
            },
            creatIconHandleReset(name){
                let type= this.creatIconFormValidate.type;
                this.$refs[name].resetFields();
                if(this.isCreate==false){
                    this.creatIconFormValidate.type=type
                }
            },
            handleUploadIcon(file){
                // if(this.creatIconFormValidate.file === null){
                //     this.creatIconFormValidate.file = file;
                // }else{
                //     return false
                // }
                 this.creatIconFormValidate.file = file;
            },
            uploadProgrress(file){
                this.isUploading = file.percent === 100 ? false : true
            },
            // 移除上传列表中的文件
            removeFile(file,fileList){
                this.creatIconFormValidate.file = null
            },
            // 修改
            modifyIcon(name){
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        let param = {
                            name:this.creatIconFormValidate.name,
                            visibility:this.creatIconFormValidate.isshare,
                            description:this.creatIconFormValidate.desc,
                            id:this.iconId,
                            type:this.creatIconFormValidate.type,
                        }
                        this.addIconBtnLoading = true
                        this.setDisabled = true
                        modifyIcon(param,param.id)
                            .then(res=>{
                                if(res.data.code == 1){
                                    this.$Message.success({
                                        content:'修改成功！',
                                        duration:3,
                                    });
                                    setTimeout(()=>{
                                        this.returnImage()
                                    },3000)
                                }else {
                                    this.$Message.error({
                                        content:res.data.message,
                                        duration:3,
                                    });
                                    this.setDisabled = false
                                }
                                this.addIconBtnLoading = false
                            })
                            .catch(err=>{
                                console.log(err)
                                this.$Message.error('服务连接失败！');
                                this.addIconBtnLoading = false
                                this.setDisabled = false
                            })
                    }else {
                        this.$Message.error('请完善信息！');
                    }
                })
            },
            onUploadError(res){
                this.$Message.error({
                    content:res.message,
                    duration:3,
                });
            },
            onUploadSuccess(res){
                if(res.code===1){
                    this.imgUrl = res.data
                    this.showPath = res.info.originalName
                }else{
                    this.$Message.error({
                        // content:'icon上传失败!',
                        content: res.message,
                        duration:3
                    })
                }
        }
        },
        beforeDestroy(){
            this.setDisabled=false
        },
    }
</script>
<style scoped>
    .page-content{
        background-color: #fff;
        border-radius: 10px;
    }
    .img-header{
        display: flex;
        justify-content: space-between;
        padding: 20px 20px 0 20px;
    }
    .addressIcon{
        display: inline-block;
        height: 14px;
        width: 12px;
        background: url("../../assets/globalIcon/addressIcon.png") no-repeat center;
        background-size: 100% 100%;
        margin-bottom: -1px;
    }
    .content-wrap{
        overflow-x: hidden;
        overflow-y: auto;
        padding: 0 20px;
        height: calc(100% - 96px);
    }
    .too{
        position: absolute;
        left: 113px;
        top: -1px;
    }
    .ios-alert{   
        /* position: absolute;
        top: -44px;
        right: -404px; */
        color: orange;
        font-size: 16px;
        cursor: pointer;
    }
</style>
